package com.hn658.groupshare.core.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.hn658.framework.common.AbstractBusinessObject;
import com.hn658.framework.security.cryptography.Base64;
import com.hn658.framework.security.cryptography.Digests;
import com.hn658.groupshare.common.entity.UserInfoEO;
import com.hn658.groupshare.core.dao.db.IUserInfoDBDAO;
import com.hn658.groupshare.core.dao.redis.IUserInfoRedisDAO;
import com.hn658.groupshare.core.service.IAccountManager;

@Component
public class AccountServiceImpl extends AbstractBusinessObject implements IAccountManager{
	@Autowired
	IUserInfoDBDAO userInfoDBDAO;
	
	@Autowired
	IUserInfoRedisDAO userInfoRedisDAO;
	
	@Override
	@Transactional
	public UserInfoEO register(UserInfoEO userInfoEO) {
		// 先对要保存的用户密码明文进行加密
		String passwordWithCrypt = encyptPassword(userInfoEO.getPassword(),
				userInfoEO.getLoginAccount());
		userInfoEO.setPassword(passwordWithCrypt);

		// 保存用户
		userInfoEO.setCreateTime(new Date());
		userInfoEO.setLastUpdateTime(new Date());
		userInfoEO.setIsDeleted(false);
		userInfoDBDAO.insert(userInfoEO);
		userInfoRedisDAO.saveUser(userInfoEO);
		
		return userInfoEO;
	}

	@Override
	@Transactional
	public void modifyPassword(UserInfoEO userInfoEO, String newPassword) {
		// 先对要保存的用户密码明文进行加密
		String passwordWithCrypt = encyptPassword(newPassword, userInfoEO.getLoginAccount());
		userInfoEO.setPassword(passwordWithCrypt);
		
		// 更新DB
		UserInfoEO modifyPdUserEO = new UserInfoEO();
		modifyPdUserEO.setId((Long)userInfoEO.getId());
		modifyPdUserEO.setPassword(passwordWithCrypt);
		modifyPdUserEO.setLastUpdateTime(userInfoEO.getLastUpdateTime());
		userInfoDBDAO.update(modifyPdUserEO);
		// 更新redis
		userInfoRedisDAO.saveUser(userInfoEO);
	}
	
	/**
	 * 加密密码
	 * @param clearTextPwd
	 * @param userLoginName
	 * @return
	 */
	public static String encyptPassword(String clearTextPwd,
			String userLoginName) {
		return Base64.encodeBase64Binrary(Digests.sha1(clearTextPwd.getBytes(),
				userLoginName.getBytes()));
	}

}
